let tempPath = []; //临时路径全局变量
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    signPic:{ //当有图片链接时，首先显示签名图片
      type:String,
      value:''
    },
  },
  options:{
　　multipleSlots: true
  },
  /**
   * 组件的初始数据
   */
  data: {
    showCanvas: true,
    colorBlocks: ['#FF0000', '#FF4081', '#FFA000', '#FFEB3B', '#00BCD4', '#2196F3', '#9E9E9E', '#000000'],
    color: '#000000',
    strokeWidth: 6,
    ctx: null,
    timeStamp: -1000,
    paths: [], // 路径二维数组
    tempFilePath: '',
  },
  lifetimes: {
  
    attached: function() {
    },
    ready: function() { //初始化画布
      let ctx = wx.createCanvasContext('canvas-handwriting', this);
      ctx.setFillStyle('#fff')
      ctx.fillRect(0, 0, 1000, 1000)
      ctx.setLineWidth(this.data.strokeWidth)
      ctx.draw()
      this.setData({ctx})
    },
    detached: function() {
    },
  },
  pageLifetimes: {
    show: function() {
    },
    hide: function() {
    },
    resize: function(size) {
    }
  },
  methods: {
    clearHandWriting: function() { //清空画布
      this.setData({
        tempFilePath: '',
        timeStamp: -1000,
        showCanvas:true,
        paths: [],
        signPic:null
      })
      let ctx = this.data.ctx;
      ctx.clearRect(0, 0, 1000, 1000);
      ctx.setFillStyle('#fff')
      ctx.setLineWidth(this.data.strokeWidth)
      ctx.fillRect(0, 0, 1000, 1000)
      ctx.draw();
    },
    finishDraw: function() { //完成绘制，将路径转为临时图片
      let _this = this;
      wx.canvasToTempFilePath({
        canvasId: 'canvas-handwriting',
        fileType: 'jpg',
        quality: 1.0,
        success(res) {
          _this.setData({
            showCanvas: false,
            tempFilePath: res.tempFilePath
          })
          _this.triggerEvent('OnComplete', res.tempFilePath);
        },
        fail(res) {
          console.error(res)
        }
      }, this)
    },
    onTouchStart: function(event) { //每次移动，都会将新的路径追加到临时路径数组
      let point = {
        x: event.touches[0].x,
        y: event.touches[0].y
      };
      tempPath = [point];
    },
    onTouchmove: function(event) { //手指移动，在画布上绘制路径
      let point = {
        x: event.touches[0].x,
        y: event.touches[0].y
      };
      tempPath.push(point)
      let ctx = this.data.ctx;
      ctx.moveTo(tempPath[tempPath.length - 2].x, tempPath[tempPath.length - 2].y)
      ctx.setLineCap('round')
      ctx.lineTo(point.x, point.y)
      ctx.stroke()
      ctx.draw(true )
    },
    onTouchEnd: function(event) { // 手指离开，清空临时路径
      let paths = this.data.paths;
      paths.push(tempPath);
      tempPath = [];
      this.setData({paths})
    },
    onError: function(event) {
      console.error('onError ----> ', event)
    },
  }
})